package iotwisp.base.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {

	@Autowired
	private static ApplicationContext applicationContext;
	@Autowired
	private Environment env;

	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	public String getEnvStr() {
		return env.getProperty("spring.profiles.active");
	}

	public String getEnvPropertie(String key) {
		return env.getProperty(key);
	}

	// public static String getEnvPropertieStatic(String key) {
	// return getInstance().getEnvPropertie(key);
	// }

	public void setApplicationContext(ApplicationContext applicationContext) {
		SpringContextUtil.applicationContext = applicationContext;
	}

	public static Object getBean(String beanName) {
		
		Object bean = null;
				
		int times = 0;
		while (applicationContext == null && times < 50) {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				log.error(e.getMessage(), e);
			}
			times++;
		}
		bean = applicationContext.getBean(beanName);
		return bean;
	}

	public static SpringContextUtil getInstance() {
		while (applicationContext == null) {
			try {
				System.out.println("context null:");
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				log.error(e.getMessage(), e);
			}
		}
		return (SpringContextUtil) applicationContext.getBean("springContextUtil");
	}

	// public static String getEnvStatic() {
	// return getInstance().getEnvStr();
	// }
}